package org.dizena.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Slf4j
@Component
public class EmailSendUtil
{
    private final String account = "";
    private final String passWord = "";
    @Value("${dizena.smtp.host}")
    private String smtp;

    public void sendMail(String email, String title, String content)
    {
        Properties props = new Properties();
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", smtp);// 用户主机
        Session session = Session.getInstance(props, new Authenticator()
        {
            protected PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(account, passWord);// 获取用户名和密码
            }
        });

        Message msg = new MimeMessage(session);
        session.setDebug(false);// 查看调试信息:true,不查看：false;
        try
        {
            msg.setFrom(new InternetAddress(account));
            msg.setSubject(title);
            msg.setRecipients(RecipientType.TO, InternetAddress.parse(email));// 多个收件人
            msg.setContent(content, "text/html;charset=utf-8");// 文本/指定文本类型，字符集
            Transport.send(msg);
        } catch (javax.mail.MessagingException e)
        {
            log.error(e.getMessage());
            // 发送失败
        } // 发送端
    }
}
